package pers.lance.merchant.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.lance.merchant.jms.JmsSender;
import pers.lance.merchant.pojo.Customer;
import pers.lance.merchant.service.CustomerService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 8:55 PM 7/30/2018
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    CustomerService customerService;
    @Autowired
    JmsSender jmsSender;

    @PostMapping("/add")
    @ResponseBody
    public Customer add(MultipartFile uploadFile, Customer customer, HttpServletRequest request) {
        String pic_path = request.getServletContext().getRealPath("\\images");
        String prefix = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        File targetFile = new File(pic_path, fileName + prefix);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            uploadFile.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        customer.setImg(fileName + prefix);
        Customer customerSql = customerService.addCustomer(customer);

        jmsSender.send(customer);
        return customerSql;
    }
}
